package itbour.onetouchshow.adapter;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

import itbour.onetouchshow.R;
import itbour.onetouchshow.utils.L_;

/**
 * Created by peterhu on 2017/5/12.
 */

public class TableAdapter<T> extends BaseAdapter {


    private static final java.lang.String TAG = "TableAdapter";
    public GriddataChangeLisener dataChangeLisener;
    public EditText nowFocus;
    private int headerBackColor = Color.argb(255, 216, 43, 43);
    private int headerTextColor = Color.argb(255, 255, 255, 255);
    private int SelectedBackColor = Color.argb(255, 255, 142, 92);
    private int SelectedTextColor = Color.argb(255, 255, 255, 255);
    private int HightedBackColor = Color.argb(255, 255, 222, 173);
    private int HightedTextColor = Color.argb(255, 33, 33, 33);
    private int CellBackColor = Color.argb(255, 255, 255, 255);
    private int CellTextColor = Color.argb(255, 33, 33, 33);
    private ArrayList<ArrayList<String>> data;
    private Context mContext;
    private EditText lastEditText;
    private Integer lastRow;
    private Integer lastColumn;
    private Integer count;
    private Integer rawCount;
    //用于更新微调库
    private Integer columnsCount;

    public TableAdapter(Context context, ArrayList<ArrayList<String>> data) {
        super();
        this.mContext = context;
        this.data = data;
        if (data != null && data.size() != 0 && data.get(0).size() != 0) {
            this.rawCount = data.size();
            this.columnsCount = data.get(0).size();
            this.count = rawCount * columnsCount;
            L_.i(TAG, "count ===" + count);
        }

    }

    public Integer getRawCount() {
        return rawCount;
    }

    public Integer getColumnsCount() {
        return columnsCount;
    }

    public void refreshData() {
        if (data != null && data.size() != 0 && data.get(0).size() != 0) {
            this.rawCount = data.size();
            this.columnsCount = data.get(0).size();
            this.count = rawCount * columnsCount;
            L_.i(TAG, "count ===" + count);
        }
    }


    public void updateHightInformation() {
        if (lastEditText != null) {

            lastEditText.setFocusable(false);
            lastEditText.setFocusableInTouchMode(false);
            // 设置 cell 背景色
            if (lastRow != 0) {
                lastEditText.setBackgroundColor(CellBackColor);
                lastEditText.setTextColor(CellTextColor);
            } else {
                lastEditText.setBackgroundColor(headerBackColor);
                lastEditText.setTextColor(headerTextColor);
            }

            lastEditText = null;
        }
    }

    public void setDateChangeLisener(GriddataChangeLisener lisener) {
        this.dataChangeLisener = lisener;
    }

    @Override
    public int getCount() {

        return this.count;
    }

    public ArrayList<String> getRawDataAtPostition(int rawPosition) {
        ArrayList<String> designOrPrintTableBeanV54Row = data.get(rawPosition);
        return designOrPrintTableBeanV54Row;
    }

    public String getColmnsDataAtPostion(int rawPosition, int columnsPostion) {
        if (rawPosition <= data.size() - 1) {
            ArrayList<String> rawData = data.get(rawPosition);
            List<String> children = rawData;
            if (children != null) {
                if (columnsPostion <= children.size() - 1) {
                    String columnData = children.get(columnsPostion);
                    return columnData;
                }
            }
        }
        return null;
    }

    public String getColmnsDataVale(int position) {

        if (getItem(position) != null) {
            String quickEditActRootValueText = getItem(position);
            return quickEditActRootValueText;
        }
        return null;
    }

    @Override
    public String getItem(int position) {

        Integer row = position / columnsCount;
        Integer column = position % columnsCount;
        String colmnsDaraArPostion = getColmnsDataAtPostion(row, column);
        return colmnsDaraArPostion;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;

        final Integer row = position / columnsCount;
        final Integer column = position % columnsCount;

//        if (convertView == null) {
        convertView = View.inflate(mContext, R.layout.table_grid_item, null);
        holder = new ViewHolder();
        convertView.setTag(holder);
        holder.tv_item = convertView.findViewById(R.id.tv_item);
        final EditText tv_item = holder.tv_item;
        holder.ll_item = convertView.findViewById(R.id.ll_item);
//        } else {
//            holder = (ViewHolder) convertView.getTag();
//        }
        //此处设置header和cell颜色
        final String text = getColmnsDataVale(position);
        String tip = "";
        //todo: 增加最大个数
        int max = 20;

        boolean firstCount = position / columnsCount == 0;
        if (!firstCount) {
            tv_item.setBackgroundColor(CellBackColor);
            tv_item.setTextColor(CellTextColor);
        } else {
            tv_item.setBackgroundColor(headerBackColor);
            tv_item.setTextColor(headerTextColor);
        }
        final LinearLayout linearL = holder.ll_item;
        //字数的限制
        tv_item.setFilters(new InputFilter[]{new InputFilter.LengthFilter(max * 5)});
        tv_item.setHint(tip);
        if (text != null) {
            tv_item.setText(text);
        }

        // 解决editText 滚动
        tv_item.setOnTouchListener(new View.OnTouchListener() {

            // 判断是否能滚动
            private boolean canVerticalScroll(EditText editText) {
                //滚动的距离
                int scrollY = editText.getScrollY();
                //控件内容的总高度
                int scrollRange = editText.getLayout().getHeight();
                //控件实际显示的高度
                int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
                //控件内容总高度与实际显示高度的差值
                int scrollDifference = scrollRange - scrollExtent;
                if (scrollDifference == 0) {
                    return false;
                }
                return (scrollY > 0) || (scrollY < scrollDifference - 1);
            }

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                EditText text = (EditText) v;
                // textView 可滚动, 且当前 textView 是第一响应者
                if (canVerticalScroll(text) && text.isFocusable()) {
                    text.getParent().requestDisallowInterceptTouchEvent(true);
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        text.getParent().requestDisallowInterceptTouchEvent(false);
                    }
                }
                return false;
            }
        });

        tv_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText edit = (EditText) v;
                if (lastEditText != null) {

                    // 设置上个 cell 的样式
                    if (lastRow != 0) {
                        lastEditText.setBackgroundColor(CellBackColor);
                        lastEditText.setTextColor(CellTextColor);
                    } else {
                        lastEditText.setBackgroundColor(headerBackColor);
                        lastEditText.setTextColor(headerTextColor);
                    }
                    lastEditText.setFocusable(false);
                    lastEditText.setFocusableInTouchMode(false);
                    LinearLayout fatherV = (LinearLayout) lastEditText.getParent();
                    fatherV.setEnabled(true);
                    if (dataChangeLisener != null) {
                        dataChangeLisener.dataChangeFrom(lastRow, lastColumn, lastEditText.getText() + "");
                    }
                }

                edit.setFocusableInTouchMode(true);
                edit.setFocusable(true);
                edit.setCursorVisible(true);
                edit.requestFocus();


                InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(edit, InputMethodManager.SHOW_FORCED);
//                edit.setBackgroundColor(SelectedBackColor);
//                edit.setTextColor(SelectedTextColor);
                lastEditText = edit;
                lastRow = row;
                lastColumn = column;
                linearL.setEnabled(false);
//                Toast.makeText(mContext, "点击了编辑框", Toast.LENGTH_LONG).show();
            }
        });

        tv_item.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                EditText edit = (EditText) v;
                if (edit.isFocusable()) {
                    edit.setFocusable(false);
                    edit.setFocusableInTouchMode(false);
                }
                edit.setCursorVisible(false);
                if (lastEditText != null) {

//                    //此处设置header和cell颜色
                    String text1 = text;
//                    String model = (String) list.get(row).get(column);


                    boolean firstCount = lastRow == 0;
                    // 设置上个 cell 的样式
                    if (!firstCount) {
                        lastEditText.setBackgroundColor(CellBackColor);
                        lastEditText.setTextColor(CellTextColor);
                    } else {
                        lastEditText.setBackgroundColor(headerBackColor);
                        lastEditText.setTextColor(headerTextColor);
                    }

                    if (lastEditText.isFocusable()) {
                        lastEditText.setFocusable(false);
                        lastEditText.setFocusableInTouchMode(false);
                        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(lastEditText.getWindowToken(), 0);
                    }

                    LinearLayout fatherV = (LinearLayout) lastEditText.getParent();
                    fatherV.setEnabled(true);

                    if (dataChangeLisener != null) {
//                        Toast.makeText(mContext, "选中第" + row + "行"  + column + "列" , Toast.LENGTH_LONG).show();
                        dataChangeLisener.dataChangeFrom(row, column, lastEditText.getText() + "");
                    }
                }
                edit.setBackgroundColor(HightedBackColor);
                edit.setTextColor(HightedTextColor);
                lastEditText = edit;
                lastRow = row;
                lastColumn = column;

                if (dataChangeLisener != null) {

                    dataChangeLisener.rowAndColumnManupulate(row, column, v);
                }
                return true;
            }
        });

        //表格的跳转逻辑
        tv_item.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    L_.i(TAG, " holder.tv_item.setOnFocusChangeListener");
//                    ((PrintEditActivity) (mContext)).setObj(obj_idList.get(0));
//                    InchingFunction.onEditTextFocusInchingPreivew(page_indexList.get(0), obj_idList.get(0), mContext, ((PrintEditActivity) (mContext)).getInchingInEditScrollview());
                    nowFocus = tv_item;
                }
            }
        });

        tv_item.addTextChangedListener(
                new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {


                    }

                    @Override
                    public void afterTextChanged(Editable s) {
//                                                        Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
                        //改变之后 直接改变结构里的
                        if (getColmnsDataVale(position) == null) {
                            return;
                        }
                        String nowString = s.toString();

                        //更新大纲数据
                        Integer row = position / columnsCount;
                        Integer column = position % columnsCount;
                        if (row <= data.size() - 1) {
                            ArrayList<String> rawData = data.get(row);
                            List<String> children = rawData;
                            if (children != null) {
                                if (column <= children.size() - 1) {
                                    children.set(column, nowString);
                                }
                            }
                        }
                    }
                }
        );

        return convertView;
    }

    public interface GriddataChangeLisener {
        void dataChangeFrom(Integer row, Integer column, String text);

        void rowAndColumnManupulate(Integer row, Integer column, View v);
    }

    class ViewHolder {
        private EditText tv_item;
        private LinearLayout ll_item;
    }

}
